﻿using Coldairarrow.Entity.BaseConfig;
using Coldairarrow.Util;
using Coldairarrow.Util.Config;
using Coldairarrow.Util.Helper;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;

namespace Coldairarrow.Business.BaseConfig
{
    public class Base_SysConfigBusiness : BaseBusiness<Base_SysConfig>, IBase_SysConfigBusiness, ITransientDependency
    {
        readonly IConfigsService  _configsService;
        public Base_SysConfigBusiness(IDbAccessor db, IConfigsService configsService)
            : base(db)
        {
            _configsService = configsService;
        }

        #region 外部接口

        public async Task<PageResult<Base_SysConfig>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<Base_SysConfig>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<Base_SysConfig, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }

            var data = await q.Where(where).GetPageResultAsync(input);
            foreach (var item in data.Data)
            { 
                item.KeyValue = AESHelper.AesDecrypt(item.KeyValue);
            }

            return  data;
        }

        public async Task<Base_SysConfig> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        /// <summary>
        /// 查询配置数据
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public async Task<List<ConfigTypeDTO>> GetConfigList()
        {
            List<ConfigTypeDTO> data = new List<ConfigTypeDTO>();
            var tList = GetIQueryable().OrderBy(x => x.Id).Select(x => x.Type).Distinct().ToList();
            foreach (var item in tList)
            {
                ConfigTypeDTO model = new ConfigTypeDTO();
                var list = await (from a in GetIQueryable().Where(x => x.Type.Equals(item)).OrderBy(x => x.Sort)
                                  select new ConfigDTO
                                  {
                                      Id = a.Id,
                                      Note = a.Note,
                                      Value = a.KeyValue
                                  }).ToListAsync();

                foreach (var item1 in list)
                {
                    if (!item1.Value.IsNullOrEmpty())
                    {
                        item1.Value = AESHelper.AesDecrypt(item1.Value);
                    }
                }

                model.TypeName = item;
                model.Configs = list;
                data.Add(model);
            }
           
            return data;
        }

        /// <summary>
        /// 更新配置数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task SetConfig(List<ConfigTypeDTO> input)
        {
            List<Base_SysConfig> list = new List<Base_SysConfig>();
            foreach (var item1 in input)
            {
                foreach (var item in item1.Configs)
                {
                    var model = await GetEntityAsync(item.Id);
                    if (!item.Value.Trim().IsNullOrEmpty())
                    {
                        model.KeyValue = AESHelper.AesEncrypt(item.Value.Trim());
                        list.Add(model);
                    }
                    else
                    {
                        model.KeyValue = "";
                        list.Add(model);
                    }
                }
            }

            _configsService.Clear();

            await UpdateAsync(list);
        }

        public async Task AddDataAsync(Base_SysConfig data)
        {
            if (!data.KeyValue.Trim().IsNullOrEmpty())
            {
                data.KeyValue = AESHelper.AesEncrypt(data.KeyValue.Trim());
            }

            var aCount = GetIQueryable().Where(x => x.KeyName.Equals(data.KeyName) || x.Note.Equals(data.Note)).Count();
            if (aCount > 0)
            {
                throw new BusException("插入失败，说明或键名不能重复！",412);
            }

            _configsService.Clear();

            await InsertAsync(data);
        }

        public async Task UpdateDataAsync(Base_SysConfig data)
        {
            if (!data.KeyValue.Trim().IsNullOrEmpty())
            {
                data.KeyValue = AESHelper.AesEncrypt(data.KeyValue.Trim());
            }

            var aCount = GetIQueryable().Where(x =>!x.Id.Equals(data.Id) && (x.KeyName.Equals(data.KeyName) || x.Note.Equals(data.Note))).Count();
            if (aCount > 0)
            {
                throw new BusException("插入失败，说明或键名不能与其他项重复！", 412);
            }

            _configsService.Clear();

            await UpdateAsync(data);
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            _configsService.Clear();

            await DeleteAsync(ids);
        }

        #endregion

        #region 私有成员

        #endregion
    }
}